//
//  FirstViewController.m
//  MeiShiDa
//
//  Created by zby on 15/6/30.
//  Copyright (c) 2015年 zby. All rights reserved.
//

#import "FirstViewController.h"
#import "CellModel1.h"
#import "CellModel2.h"
#import "TableViewCell1.h"
#import "TableViewCell2.h"
#import <CoreLocation/CoreLocation.h>
@interface FirstViewController ()
@property (nonatomic,strong) CLLocationManager* locationManager;
@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.barTintColor=[UIColor colorWithRed:0.724 green:0.389 blue:1.000 alpha:1.000];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.724 green:0.389 blue:1.000 alpha:1.000];
    self.navigationItem.title=@"首页";
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self askForLocation];
    });
    [self.navigationController.navigationBar setShadowImage:[UIImage imageNamed:@"d81c5adc757cde186f1844c17a8846c1"]];
 
    // 判断网络状态
    [self whetherHasNetwork];
    [self.tableView registerClass:[TableViewCell1 class] forCellReuseIdentifier:@"Cell1"];
    [self.tableView registerClass:[TableViewCell2 class] forCellReuseIdentifier:@"Cell2"];
 // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)askForLocation{
    self.locationManager = [[CLLocationManager alloc] init];
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
    }
}
-(void)whetherHasNetwork{
////////////////////////////////////////////////////////////////////////////////
//使用Reachability 进行网络状态判断
//    Reachability* reachAbility = [Reachability reachabilityWithHostName:@"www.baidu.com"];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
//    [reachAbility startNotifier];
////////////////////////////////////////////////////////////////////////////////
    
  //使用AFNetworking进行网络状态判断
    AFNetworkReachabilityManager* reachManager = [AFNetworkReachabilityManager sharedManager];
    [reachManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
            {
                [SVProgressHUD showErrorWithStatus:@"无连接，进入离线模式" maskType:SVProgressHUDMaskTypeGradient];
                [self getDataFromDB];
            }
                break;
                case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                
            }
                break;
                case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                
            }
                break;
            default:
                break;
        }
    }];
    //开始监控
    [reachManager startMonitoring];
    
}

//-(void)reachabilityChanged:(NSNotification*)note{
//    Reachability* reach = [note object];
//    if ([reach isReachable]) {
//        NSLog(@"网络可用");
//    }
//    else{
//        NSLog(@"网络不可用");
//        [self getDataFromDB];
//    }
//}

-(void)getDataFromDB{
    DBmanager* dbManager = [DBmanager shareDBmanager];
    FMDatabase* db = [dbManager openOrCreateDB];
    FMResultSet* resultSet1 = [db executeQuery:@"select * from ModelData1"];
    FMResultSet* resultSet2 = [db executeQuery:@"select * from ModelData2"];
    self.arr1 = [NSMutableArray arrayWithCapacity:0];
    self.arr2 = [NSMutableArray arrayWithCapacity:0];
    while ([resultSet1 next]) {
        CellModel1* model1 = [[CellModel1 alloc] init];
        model1.title = [resultSet1 stringForColumn:@"Title"];
        model1.titlepic = [resultSet1 stringForColumn:@"Picture"];
        [self.arr1 addObject:model1];
    }
    while ([resultSet2 next]) {
        CellModel2* model2 = [[CellModel2 alloc] init];
        model2.title = [resultSet2 stringForColumn:@"Title"];
        model2.titlepic = [resultSet2 stringForColumn:@"Picture"];
        model2.descr = [resultSet2 stringForColumn:@"Descr"];
        [self.arr2 addObject:model2];
    }
}


//@"insert into ModelData2 (ModelID,Title,Picture,Descr) values (?,?,?,?)

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Return the number of rows in the section.
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row == 0) {
        TableViewCell1* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell1" forIndexPath:indexPath];
        CellModel1* model = self.arr1[indexPath.section];
        NSString* str = model.titlepic;
        [cell.CellImageView sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:nil];
        cell.title.text = model.title;
        return cell;
    }
    else{
        TableViewCell2* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell2" forIndexPath:indexPath];
        long a = indexPath.section * 3;
        CellModel2* model = self.arr2[indexPath.row-1+a];
        NSString* str = model.titlepic;
        [cell.CellImageView sd_setImageWithURL:[NSURL URLWithString:str]];
        cell.descr.text = model.descr;
        cell.title.text = model.title;
        return cell;
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [[UIScreen mainScreen] bounds].size.height/6;
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
